package com.flyme.module.file.provider.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyme.common.core.constants.CommonConstants;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.common.core.utils.SpringContextHolder;
import com.flyme.common.core.utils.TreeUtils;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
import com.flyme.module.file.client.entity.SysCataLog;
import com.flyme.module.file.client.event.CourseUploadEvent;
import com.flyme.module.file.provider.mapper.SysCataLogMapper;
import com.flyme.module.file.provider.service.SysCataLogService;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author: flyme
 * @date: 2018/3/7 15:27
 * @desc: 课程目录接口实现
 */
@Service
public class SysCataLogServiceImpl extends BaseServiceImpl<SysCataLogMapper, SysCataLog> implements SysCataLogService {


    @Override
    public List<Map<String, Object>> selectCataLog(Long courseId) {
        CriteriaQuery qw = new CriteriaQuery<EntityMap>();
        qw.select("id", "cataLogTitle title", "cataLogNo", "parentId", "videoId", "status", "cataLogUrl", "isParent", "isFree", "sortOrder");
        qw.eq("courseId", courseId);
        qw.orderByAsc("sortOrder");
        List list = listMaps(qw);
        return TreeUtils.buildTree(list, "0");

    }


    @Override
    public Boolean addCataLog(SysCataLog cataLog) {
        Long parentId = cataLog.getParentId();
        SysCataLog parent = getById(parentId);
        cataLog.setParentId(ObjectUtils.isEmpty(parentId) ? 0L : parentId);
        cataLog.setSortOrder(ObjectUtils.isEmpty(cataLog.getSortOrder()) ? new BigDecimal("0") : cataLog.getSortOrder());
        if (parentId.equals(0L)) {
            Integer count = count(q().eq("parentId", cataLog.getParentId()).eq("courseId", cataLog.getCourseId()));
            BigDecimal sortOrder = ObjectUtils.gertBigDecimal(new BigDecimal(count), "0");
            sortOrder = sortOrder.add(new BigDecimal(1));
            cataLog.setCataLogTitle("一级目录");
            cataLog.setStatus(CommonConstants.ENABLED);
            cataLog.setSortOrder(sortOrder.subtract(new BigDecimal(1)));
            cataLog.setIsParent(1);
        } else {
            Integer count = count(q().eq("parentId", parent.getId()));
            BigDecimal sortOrder = ObjectUtils.gertBigDecimal(new BigDecimal(count), "0");
            sortOrder = sortOrder.add(new BigDecimal(1));
            cataLog.setSortOrder(sortOrder.subtract(new BigDecimal(1)));
            cataLog.setCataLogTitle("二级目录");
            cataLog.setStatus(CommonConstants.ENABLED);
            cataLog.setIsParent(0);
        }
        return save(cataLog);
    }

    @Override
    public Boolean updateCataLog(SysCataLog cataLog) {
        String fileUrl = cataLog.getCataLogUrl();
        String videoId = cataLog.getVideoId();
        if (ObjectUtils.isNotEmpty(fileUrl)) {
            Integer index = fileUrl.indexOf("view");
            if (index > -1) {
                String fileId = fileUrl.substring(index + 5);
                cataLog.setFileId(fileId);
            } else {
                Integer first = fileUrl.indexOf("/");
                Integer two = fileUrl.substring(first + 2).indexOf("/");
                String url = fileUrl.substring(first + 2).substring(two + 1);
                videoId = url.substring(0, 32);
                cataLog.setVideoId(videoId);
            }
        }
        //同步过的不在执行上传阿里云,后续如果修改视频需在前台添加强制更新操作
        if (ObjectUtils.isEmpty(videoId)) {
            applicationContext.publishEvent(new CourseUploadEvent(this, cataLog, SpringContextHolder.getRequest()));
        }
        return saveOrUpdate(cataLog);
    }

    @Override
    public ResultBody delById(Long cataLogId) {
        SysCataLog cataLog = getById(cataLogId);
        if (cataLog.getIsParent().equals(1)) {
            int n = count(q().eq("parentId", cataLogId));
            if (n > 0) {
                return ResultBody.failed("请先删除子节点");
            }
        }
        removeById(cataLogId);
        return ResultBody.success("刪除成功");
    }

    /**
     * 根据视频id查询目录
     */
    public SysCataLog findByVideoId(String videoId) {
        return getOne(q().eq(true, "videoId", videoId), false);
    }

    /**
     * 查询一级目录
     */
    public List<Map<String, Object>> selectOne(Long courseId) {
        return listMaps(q().eq("courseId", courseId).eq("parentId", 0).eq("status", 1).orderByAsc("sortOrder"));
    }

    /**
     * 查询二级目录（即视频）
     */
    public List<SysCataLog> selectTwo(String catalogId) {
        return list(q().eq("parentId", catalogId).eq("status", 1).orderByAsc("sortOrder"));
    }

    /**
     * 查询二级目录（即视频）
     */
    public List<EntityMap> selectTwo2(String catalogId, String title, String cataLogimg) {
        PagerInfo pagerInfo = new PagerInfo();
        pagerInfo.setPageSize(1000);
        pagerInfo.setPageNumber(1);
        CriteriaQuery queryWrapper = new CriteriaQuery<EntityMap>(pagerInfo);
        queryWrapper.select("*,'" + title + "' oneTitle,'" + cataLogimg + "' cataLogimg");
        queryWrapper.eq("parentId", catalogId);
        queryWrapper.eq("status", 1);
        queryWrapper.isNotNull("videoId");
        queryWrapper.orderByAsc("sortOrder");
        return (List<EntityMap>) pageList(queryWrapper).getRows();
    }

    @Override
    public Boolean updateSortNo(Long courseId, Long parentId, Integer n1, Integer n2) {
        EntityMap map = new EntityMap();
        map.put("courseId", courseId);
        map.put("parentId", parentId);
        map.put("n1", n1);
        map.put("n2", n2);
        return baseMapper.updateSortNo(map);
    }

    /**
     * 根据课程id查询该课程下视频数量
     */
    public Integer countByCourseId(Long courseId) {
        return count(q().eq(true, "courseId", courseId).ne(true, "parentId", 0));
    }

    /**
     * 查询多个课程下所有视频数量
     */
    public Integer countByCourseIds(String[] courseIds) {
        Long[] strArrNum = new Long[courseIds.length];
        for(int i=0;i<courseIds.length;i++){
            strArrNum[i] = Long.valueOf(courseIds[i]);
        }
        return count(q().in(true, "courseId", strArrNum).ne(true, "parentId", 0));
    }


    /**
     * 根据课程查询该课程下的收费目录
     */
    public List<SysCataLog> selectByCouse(Long courseId){
        return list(q().eq("courseId", courseId).eq("isFree", 1));
    }

    /**
     * 将该课程下的所有目录改为免费
     */
    public boolean updateFree(Long courseId){
        UpdateWrapper c = new UpdateWrapper();
        return update(c.set(true, "isFree", 0).eq(true, "courseId", courseId).ne(true, "isFree", 0));
    }

}
